package org.lboot.s3.test;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.lboot.s3.client.S3Client;
import org.lboot.s3.test.params.FileUploadParams;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@Slf4j
@RestController
@RequestMapping("s3")
@AllArgsConstructor
@Api(tags = "对象方法测试")
public class S3ObjectTestController {
    S3Client s3Client;




    @PostMapping("object")
    @ApiOperation(value = "对象新建",notes = "")
    public Object objectCreate(FileUploadParams params){
        s3Client.putObject(params.getBucketName(), params.getFileName(), params.getFile());
        return "上传成功";
    }


    @GetMapping("object/{bucketName}/{objectName}/info")
    @ApiOperation(value = "对象信息")
    public Object objectInfo(@PathVariable("bucketName") String bucketName, @PathVariable("objectName") String objectName){
        return s3Client.getObjectInfo(bucketName, objectName);
    }

    @GetMapping("object/{bucketName}/{objectName}/url")
    @ApiOperation(value = "对象访问地址")
    public Object objectUrl(@PathVariable("bucketName") String bucketName, @PathVariable("objectName") String objectName){
        return s3Client.getObjectURL(bucketName, objectName, 3);
    }

    @GetMapping("object/{bucketName}/{objectName}")
    @ApiOperation(value = "对象下载")
    @SneakyThrows
    public ResponseEntity<byte[]> objectDownload(@PathVariable("bucketName") String bucketName, @PathVariable("objectName") String objectName){
        return s3Client.download(bucketName, objectName);
    }

    @DeleteMapping("object/{bucketName}/{objectName}")
    @ApiOperation(value = "对象删除",notes = "")
    public Object objectDelete(@PathVariable("bucketName") String bucketName, @PathVariable("objectName") String objectName){
        if (s3Client.doesObjectExist(bucketName, objectName)){
            s3Client.deleteObject(bucketName, objectName);
            return true;
        }
        return "桶或对象不存在";
    }

    @DeleteMapping("object/{bucketName}/prefix/{prefix}")
    @ApiOperation(value = "对象(前缀)删除",notes = "")
    public Object objectPrefixDelete(@PathVariable("bucketName") String bucketName, @PathVariable("prefix") String prefix){
        return s3Client.deleteObjectsByPrefix(bucketName,prefix);
    }

    @GetMapping("bucket/{bucketName}/objects")
    @ApiOperation(value = "对象列表",notes = "")
    public Object listObjects(@PathVariable("bucketName") String bucketName){
        return s3Client.listObjects(bucketName);
    }
}

